package com.icehand.payment.pay.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.icehand.common.code.PaymentCode;
import com.icehand.common.constants.CommonConstants;
import com.icehand.common.enums.TradeStatusEnum;
import com.icehand.common.model.BaseOrder;
import com.icehand.mybatis.payment.domain.PayNotifyRecord;
import com.icehand.mybatis.payment.mapper.PayNotifyRecordMapper;
import com.icehand.payment.model.NotifyWrapper;
import com.icehand.payment.model.PayWrapper;
import com.icehand.payment.pay.Pay;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * 支付宝基础支付类
 * @author icehand
 */
@Slf4j
public abstract class BaseAliPay implements Pay {
    private static final String VERIFY_NOTIFY_URL = "https://mapi.alipay.com/gateway.do?service=notify_verify&partner=%s&notify_id=%s";
    private final RestTemplate restTemplate;
    private final PayNotifyRecordMapper payNotifyRecordMapper;

    protected BaseAliPay(RestTemplate restTemplate, PayNotifyRecordMapper payNotifyRecordMapper) {
        this.restTemplate = restTemplate;
        this.payNotifyRecordMapper = payNotifyRecordMapper;
    }

    @Override
    public void payNotify(NotifyWrapper notifyWrapper) {
        Map<String,String> alipayNotifyMap = getAlipayNotifyData(notifyWrapper.getRequest());
        if(alipayNotifyMap.isEmpty()){
            notifyWrapper.getBizResult().error(PaymentCode.PAY_NOTIFY_PARAM_ERROR);
            return;
        }

        //校验签名
        String sign = alipayNotifyMap.get(CommonConstants.K_SIGN);
        String signContent = AlipaySignature.getSignCheckContentV2(alipayNotifyMap);
        boolean verified;
        try {
            verified = AlipaySignature.rsaCheck(signContent,sign,notifyWrapper.getConfig().getString(CommonConstants.K_ALIPAY_PUBLIC_KEY),
                    notifyWrapper.getConfig().getString(CommonConstants.K_CHARSET),
                    notifyWrapper.getConfig().getString(CommonConstants.K_SIGN_TYPE));

        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.error("check alipay notify sign error: {}",e);
            notifyWrapper.error(PaymentCode.PAY_NOTIFY_SIGN_ERROR);
            return;
        }
        if(!verified){
            log.warn("check alipay notify sign fail, signContent:{}",signContent);
            notifyWrapper.error(PaymentCode.PAY_NOTIFY_SIGN_ERROR);
            return;
        }

        //校验notifyId
        String result = restTemplate.getForObject(String.format(VERIFY_NOTIFY_URL,notifyWrapper.getConfig().get(CommonConstants.K_PARTNER),
                alipayNotifyMap.get("notify_id")),String.class);
        if(Strings.isNullOrEmpty(result) || !CommonConstants.K_TRUE.equals(result)){
            notifyWrapper.error(PaymentCode.PAY_NOTIFY_VERIFY_FAIL);
            return;
        }

        BaseOrder baseOrder = new BaseOrder()
                .setOrderNo(alipayNotifyMap.get("out_trade_no"))
                .setAmount(new BigDecimal(alipayNotifyMap.get("total_fee")))
                .setTradeStatus(TradeStatusEnum.getAlipayTradeStatus(alipayNotifyMap.get("trade_status")))
                .setPayTime(new Date());

        if(null != payNotifyRecordMapper){
            PayNotifyRecord record = new PayNotifyRecord()
                    .setAppId(notifyWrapper.getAppId())
                    .setChannelId(notifyWrapper.getPayChannelEnum().getChannelId())
                    .setAmount(baseOrder.getAmount())
                    .setOrderNo(baseOrder.getOrderNo())
                    .setTradeNo(alipayNotifyMap.get("trade_no"))
                    .setTradeStatus(baseOrder.getTradeStatus().getStatus())
                    .setCreateTime(new Date())
                    .setNotifyData(JSONObject.toJSONString(alipayNotifyMap));
            payNotifyRecordMapper.insert(record);
        }

        notifyWrapper.getBizResult().putData(baseOrder);
    }

    protected AlipayClient createAlipayClient(PayWrapper payWrapper){
        return  new DefaultAlipayClient(payWrapper.getConfig().getString(CommonConstants.K_GATEWAY_URL),
                    payWrapper.getConfig().getString(CommonConstants.K_APP_ID),
                    payWrapper.getConfig().getString(CommonConstants.K_MERCHAT_PRIVATE_KEY),
                "json",
                    payWrapper.getConfig().getString(CommonConstants.K_CHARSET),
                    payWrapper.getConfig().getString(CommonConstants.K_ALIPAY_PUBLIC_KEY),
                    payWrapper.getConfig().getString(CommonConstants.K_SIGN_TYPE));
    }

    protected Map<String,String> getAlipayNotifyData(HttpServletRequest request){
        Map<String, String> params = Maps.newHashMap();
        Map requestParams = request.getParameterMap();
        for (Object o : requestParams.keySet()) {
            String name = (String) o;
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        return params;
    }

}
